package com.lxg.learn.utils;



import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;
import com.google.common.base.Strings;
import org.apache.shardingsphere.encrypt.exception.algorithm.EncryptAlgorithmInitializationException;
import org.apache.shardingsphere.encrypt.spi.EncryptAlgorithm;
import org.apache.shardingsphere.encrypt.spi.context.EncryptContext;
import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collection;
import java.util.Properties;


public class ShardingDataEncryptor implements EncryptAlgorithm<Object, String> {
    private byte[] secretKey;//128bit(16byte)
    private SM4 sm4;
    private Properties props;

    public ShardingDataEncryptor() {
    }


    public void init(Properties props) {
        String key = props.getProperty("sm4-type-key");
        ShardingSpherePreconditions.checkState(!Strings.isNullOrEmpty(key), () -> {
            return new EncryptAlgorithmInitializationException(this.getType(), String.format("%s can not be null or empty", "aes-key-value"));
        });
        secretKey = Base64.getDecoder().decode(key);
        sm4 = SmUtil.sm4(secretKey);
        this.props = props;
    }


    @Override
    public String encrypt(Object plainValue, EncryptContext encryptContext) {
        try {
            if (null == plainValue) {
                return null;
            } else {
                byte[] result = sm4.encrypt(String.valueOf(plainValue).getBytes(StandardCharsets.UTF_8));
                return Base64.getEncoder().encodeToString(result);
            }
        } catch (Exception var4) {
            throw var4;
        }
    }

    @Override
    public String decrypt(String cipherValue, EncryptContext encryptContext) {
        try {
            if (null == cipherValue) {
                return null;
            } else {
                if (cipherValue.isEmpty()){
                    return "";
                }
                byte[] result = sm4.decrypt(Base64.getDecoder().decode(cipherValue.toString().trim()));
                return new String(result, StandardCharsets.UTF_8);
            }
        } catch (Exception var4) {
            throw var4;
        }
    }

    @Override
    public Collection<String> getTypeAliases() {
        return EncryptAlgorithm.super.getTypeAliases();
    }

    @Override
    public String getType() {
        return "SM4-CUSTOM";
    }

    @Override
    public Properties getProps() {
        return this.props;
    }
}